package com.sengled.cloud.biz.union.mgt.service.sys.impl;


import com.sengled.cloud.biz.union.mgt.common.CommonConstant;
import com.sengled.cloud.biz.union.mgt.common.SysConstants;
import com.sengled.cloud.biz.union.mgt.common.util.Md5Util;
import com.sengled.cloud.biz.union.mgt.dao.sys.*;
import com.sengled.cloud.biz.union.mgt.model.dto.UnionUser;
import com.sengled.cloud.biz.union.mgt.model.po.*;
import com.sengled.cloud.biz.union.mgt.model.vo.*;
import com.sengled.cloud.biz.union.mgt.service.util.S3Util;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.session.ExpiringSession;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.stereotype.Service;

import com.sengled.cloud.biz.union.mgt.common.PageUtil;
import com.sengled.cloud.biz.union.mgt.model.request.SaveUserRequest;
import com.sengled.cloud.biz.union.mgt.model.request.UserListQueryRequest;
import com.sengled.cloud.biz.union.mgt.model.response.ResponseMessage;
import com.sengled.cloud.biz.union.mgt.service.sys.IUserService;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by FMC on 2017/10/27.
 */
@Service("userService")
@Transactional(value="txManager",rollbackFor = {Exception.class}, propagation = Propagation.REQUIRED)
public class UserService implements IUserService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    UserDao userDao;

    @Autowired
    ShopAccountDao shopAccountDao;

    @Autowired
    UserAccountDao userAccountDao;

    @Autowired
    UserFeedbackDao userFeedbackDao;

    @Autowired
    ShopDao shopDao;

    @Autowired
    UserAcctShopAcctDao userAcctShopAcctDao;

    @Autowired
    CurrentShopDao currentShopDao;

    @Autowired
    ModuleDao moduleDao;

    @Override
    public ResponseMessage saveOrUpdate(SaveUserRequest saveUserRequest,Long operatorId) {
        ResponseMessage rm = new ResponseMessage<>();
        if (null == saveUserRequest) {
            rm.buildParamErrorMessage();
            return rm;
        }
        if(StringUtils.isEmpty(saveUserRequest.getUserCode())||StringUtils.isEmpty(saveUserRequest.getUserName())||(saveUserRequest.getSex()==null)||(saveUserRequest.getRoleId()==null)||(saveUserRequest.getShopId()==null)){
            rm.buildParamErrorMessage();
            return rm;
        }

        try {
            User user = new User();
            BeanUtils.copyProperties(user, saveUserRequest);
            if(StringUtils.isNotEmpty(saveUserRequest.getHireDateStr())){
                user.setHireDate(strToDate(saveUserRequest.getHireDateStr()));
            }

            if(StringUtils.isNotEmpty(saveUserRequest.getLeaveDateStr())){
                user.setLeaveDate(strToDate(saveUserRequest.getLeaveDateStr()));
            }
            int ret;
            int ret1;
            
            int userNum = userDao.getUserCountByUserCode(saveUserRequest.getUserCode());
            
            if (null != user.getId()) {
                //shop.setCreateDate(new Date());
            	UserDetailVo m = userDao.selectByPrimaryKey(user.getId());
            	if(m==null){
            		  rm.buildParamErrorMessage();
                      return rm;
            	}
            	
            	if(!m.getUserCode().equals(saveUserRequest.getUserCode())&&userNum>0){
            		rm.buildUserCodeRepeatMessage();
                 	return rm;
            	}
            	
                user.setModifyDate(new Date());
                user.setSealMark(0);
                Long companyId = getCompanyId(operatorId);
                user.setOperatorId(operatorId);
                user.setCompanyId(companyId);
                ret = userDao.updateByPrimaryKey(user);
                UserRole userRole = new UserRole();
                userRole.setRoleId(saveUserRequest.getRoleId());
                userRole.setUserId(user.getId());
                userRole.setModifyDate(new Date());
                ret1 = userDao.updateRole(userRole);
            } else {
            	if(userNum>0){
            		rm.buildUserCodeRepeatMessage();
                 	return rm;
                 }
                user.setCreateDate(new Date());
                Long companyId = getCompanyId(operatorId);
                user.setOperatorId(operatorId);
                user.setCompanyId(companyId);
                //shop.setSealMark(0);
                ret = userDao.insert(user);

                UserRole userRole = new UserRole();
                userRole.setRoleId(saveUserRequest.getRoleId());
                userRole.setUserId(user.getId());
                userRole.setModifyDate(new Date());
                ret1 = userDao.insertRole(userRole);
            }
            if (0 == ret) {
                rm.buildExecuteFailMessage();
            }
            if (0 == ret1) {
                rm.buildExecuteFailMessage();
            }
            return rm;
        } catch (Exception e) {
            logger.debug(e.getMessage(), e);
            rm.buildSystemErrorMessage();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return rm;
        }
    }

    @Override
    public ResponseMessage delete(Long id) {
        ResponseMessage rm = new ResponseMessage<>();
        if (null == id || id.intValue() < 0) {
            rm.buildParamErrorMessage();
            return rm;
        }
        try {
        	//Long userAccountId = userDao.getUserAccountIdByUserId(id);
        	userDao.deleteUserAcctShopAcct(id);
        	userDao.deleteAccountRole(id);
        	userDao.deleteUserFeedback(id);
        	userDao.deleteUserRole(id);
        	userDao.deleteUserAccount(id);
            int ret = userDao.deleteByPrimaryKey(id);
//            if (0 == ret) {
//                rm.buildExecuteFailMessage();
//            }
            return rm;
        } catch (Exception e) {
            logger.debug(e.getMessage(), e);
            rm.buildSystemErrorMessage();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return rm;
        }
    }

    @Override
    public ResponseMessage<UserDetailVo> getUserDetailById(Long id) {
        ResponseMessage rm = new ResponseMessage<>();
        if (null == id || id.intValue() < 0) {
            rm.buildParamErrorMessage();
            return rm;
        }
        try {
            UserDetailVo m = userDao.selectByPrimaryKey(id);
            if (null != m) {
                rm.setData(m);
            }
            return rm;
        } catch (Exception e) {
            logger.debug(e.getMessage(), e);
            rm.buildSystemErrorMessage();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return rm;
        }
    }

    @Override
    public ResponseMessage<List<UserVo>> listUsersByPage(UserListQueryRequest q) {


        QueryData<List<UserVo>> queryData = new QueryData<List<UserVo>>();

        ResponseMessage rm = new ResponseMessage<>();
        if (null == q) {
            rm.buildParamErrorMessage();
            return rm;
        }
        try {
        	boolean isSuperManager = isSuperManager(q.getUserId());
        	q.setSuperMgr(isSuperManager);
        	
            List<UserVo> ms = userDao.listUsersByPage(q);
            Integer totalRecords = userDao.queryuserTotalRecords(q);
            if (null != ms && !ms.isEmpty()) {
                queryData.setData(ms);

            }

            queryData.setTotalCount(totalRecords);

            //int totalPages = totalRecords%q.getPageSize()==0?totalRecords/q.getPageSize():totalRecords/totalRecords+1;
            if(totalRecords>0){
                PageUtil pageUtil = new PageUtil(q.getPageNo(),
                        q.getPageSize(), totalRecords);
                queryData.setTotalPage(pageUtil.getPageCount());
                queryData.setBeginIndex(pageUtil.getStartIndex());
                queryData.setEndIndex(pageUtil.getEndIndex());
            }else{
                queryData.setTotalPage(1);
                queryData.setBeginIndex(0);
                queryData.setEndIndex(0);
            }
            queryData.setPageNo(q.getPageNo());
            queryData.setPageSize(q.getPageSize());
            rm.setData(queryData);

            return rm;
        } catch (Exception e) {
            logger.debug(e.getMessage(), e);
            rm.buildSystemErrorMessage();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return rm;
        }
    }
//
//    @Override
//    public ResponseMessage updatePassStatus(Long id) {
//        ResponseMessage rm = new ResponseMessage<>();
//        if (null == id || id.intValue() < 0) {
//            rm.buildParamErrorMessage();
//            return rm;
//        }
//        try {
//            Calendar c = Calendar.getInstance();
//            int ret = messageDao.updatePassStatus(c.getTime(), id);
//            if (0 == ret) {
//                rm.buildExecuteFailMessage();
//            }
//            return rm;
//        } catch (Exception e) {
//            logger.error(e.getMessage(), e);
//            rm.buildSystemErrorMessage();
//            return rm;
//        }
//    }
//
//    @Override
//    public Message getById(Long id) {
//        if (null == id || id.intValue() < 0) {
//            return null;
//        }
//        try {
//            Message m = messageDao.getMessageById(id);
//            if (null != m) {
//                return m;
//            }
//            return null;
//        } catch (Exception e) {
//            logger.error(e.getMessage(), e);
//            return null;
//        }
//    }

    public static Date strToDate(String str) {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = format.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    @Override
    public ResponseMessage<List<SelectBoxDataVo>> getRoleSelectData(Long userId){
        ResponseMessage rm = new ResponseMessage<>();

        try {

            Long companyId = 1L;
            //List<SelectBoxDataVo> m = userDao.getRoleSelectData();
            List<SelectBoxDataVo> m = userAccountDao.getAllRoleList(userId);
            //SelectBoxDataVo selectBoxDataVo = new SelectBoxDataVo();
            //map.put(0L, "全部");
//        	 selectBoxDataVo.setId(0L);
//        	 selectBoxDataVo.setName("全部");



//             if (null != m) {
//            	 m.set(0, selectBoxDataVo);
//             }else{
//            	 m = new ArrayList<SelectBoxDataVo>();
//            	 m.set(0, selectBoxDataVo);
//             }
            rm.setData(m);
            return rm;
        } catch (Exception e) {
            logger.debug(e.getMessage(), e);
            rm.buildSystemErrorMessage();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return rm;
        }
    }

    @Override
    public ResponseMessage<ShopAccountListVo> getUserShops(Long accountId) {
        ResponseMessage<ShopAccountListVo> rm = new ResponseMessage<ShopAccountListVo>();
        try{
            List<ShopAccountVo> shopAccountVos = userDao.getUserShops(accountId);
            ShopAccountListVo shopAccountListVo = new ShopAccountListVo();
            shopAccountListVo.setShops(shopAccountVos);
            rm.setData(shopAccountListVo);
            return rm;
        }catch (Exception e){
            rm.buildSystemErrorMessage();
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return rm;
        }
    }

    @Override
    public ResponseMessage<CurrentShopsVo> changeShop(Long id,Long accountId,String moduleCode) {
        ResponseMessage<CurrentShopsVo> rm = new ResponseMessage<CurrentShopsVo>();
        CurrentShopsVo currentShopsVo = new CurrentShopsVo();

        try {
            if(id == -1){
                //通过moduleCode查询moduleId
                Long moduleId = moduleDao.selectIdByCode(moduleCode);
                //全部，删除current_shop表中对应数据
                currentShopDao.deleteByModuleAndAccountKey(accountId,moduleId);
                currentShopsVo.setModuleCode(moduleCode);
                currentShopsVo.setName("全部");
                currentShopsVo.setCode("ALL");
                currentShopsVo.setId(-1L);
                //currentShopsVo.setAll(true);
                rm.setData(currentShopsVo);
                return rm;
            }else{
                //查询新shopId是否是accountId关联店铺
                int i = userAcctShopAcctDao.queryUserAcctShopAcctCount(id,accountId);
                if(i > 0){

                    //通过moduleCode查询moduleId
                    Long moduleId = moduleDao.selectIdByCode(moduleCode);
                    //全部，删除current_shop表中对应数据
                    currentShopDao.deleteByModuleAndAccountKey(accountId,moduleId);
                    CurrentShop currentShop = new CurrentShop();
                    currentShop.setModuleId(moduleId);
                    currentShop.setUserAccountId(accountId);
                    currentShop.setCurrentShopId(id);
                    currentShop.setCreateDate(new Date());
                    currentShopDao.insertSelective(currentShop);

                    ShopAccount sa = shopAccountDao.selectByPrimaryKey(id);
                    //ShopAccountVo sav = new ShopAccountVo();
                    currentShopsVo.setId(sa.getId());
                    currentShopsVo.setCode(sa.getShopCode());
                    currentShopsVo.setName(sa.getShopName());

                    currentShopsVo.setModuleCode(moduleCode);
                    //currentShopsVo.setShopAccountVo(sav);
                    rm.setData(currentShopsVo);
                    return rm;
                }else{
                    rm.buildParamErrorMessage();
                    return rm;
                }
            }
        }catch (Exception e){
            rm.buildSystemErrorMessage();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return rm;
        }
    }

    @Override
    public ResponseMessage changePwd(Long accountId,String oldPwd,String newPwd) {
        ResponseMessage rm = new ResponseMessage();
        try {
            //通过sessionId从redis读取用户信息
            UserAccount ua = userAccountDao.selectByPrimaryKey(accountId);
            oldPwd = Md5Util.md5(oldPwd);
            if(ua != null){
                if(oldPwd.equals(ua.getAccountPwd())){
                    //update user_account表的account_pwd
                    newPwd = Md5Util.md5(newPwd);
                    userAccountDao.updateUserPwd(accountId,newPwd);
                }else{
                    rm.buildParamErrorMessage();
                }
            }
            return rm;
        }catch (Exception e){
            rm.buildSystemErrorMessage();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return rm;
        }
    }

    @Override
    public ResponseMessage saveFeedback(String feedback,Long accountId) {
        ResponseMessage rm = new ResponseMessage();
        try{
            //通过sessionId取出userId
            //通过user_account_id查询出user_id
            UserAccount userAccount = userAccountDao.selectByPrimaryKey(accountId);
            if(userAccount != null){
                Long userId = userAccount.getUserId();
                UserFeedback userFeedback = new UserFeedback();
                userFeedback.setUserId(userId);
                userFeedback.setUserAccountId(accountId);
                userFeedback.setContent(feedback);
                userFeedback.setCreateDate(new Date());
                userFeedbackDao.insert(userFeedback);
            }else{
                rm.buildParamErrorMessage();
            }
            return rm;
        }catch (Exception e){
            rm.buildSystemErrorMessage();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return rm;
        }
    }

    @Override
    public ResponseMessage uploadUserProfile(MultipartFile profilePhoto, HttpServletRequest request ,String region ,String bucketName,Long accountId,String tmpPath) {
        ResponseMessage rm = new ResponseMessage();
        try{
            UserAccount userAccount = userAccountDao.selectByPrimaryKey(accountId);
            Long userId = userAccount.getUserId();
            CurrentUserVo currentUserVo = userDao.selectCurrentUser(userId);

            //通过Header中的sessionId，从redis中取出用户信息
            boolean b = S3Util.getInstance(region).queryBucketExist(bucketName);
            if(!b){
                S3Util.createBucket(bucketName);
            }

            String tempPath = tmpPath+File.separator+CommonConstant.FileUploadConstant.BIZ_TEMP_FILE_PATH;
            logger.debug("temp_file_picture_path:------------->" + tempPath);

            String fname = null;
            String name = null;
            String suffix = null;
            if(currentUserVo !=null && StringUtils.isNotEmpty(currentUserVo.getProfilePhoto())){
                fname = currentUserVo.getProfilePhoto();
            }else{
                String profileName = profilePhoto.getOriginalFilename();
                if (profileName.lastIndexOf(".") != -1) {
                    //name等于文件名去掉后缀拼上当前时间拼上用户名md5
                    name = profileName.substring(0, profileName.lastIndexOf("."))+new Date().toString()+userAccount.getAccountName();
                    suffix = profileName.substring(profileName.lastIndexOf(".") + 1);
                }

                name = Md5Util.md5(name);

                fname = name +"."+suffix;
                logger.debug("userId:------------->" + userId+"&&fname---------->"+fname);
                userDao.updateUserForProfile(userId,fname);
                logger.debug("update success");
            }

            //缓存文件
            File tempDir = new File(tempPath);
            if(!tempDir.exists()){
                tempDir.mkdirs();
            }

            File tempFile = new File(tempPath + File.separator + fname);
            logger.debug("tmp file：---------------->"+tempPath + File.separator + fname);
            try {
                profilePhoto.transferTo(tempFile);
            }catch (Exception e){
                e.printStackTrace();
            }
            logger.debug("upload picture to s3 ：---------------->"+"bucketName:"+bucketName+"&fname:"+fname);
            S3Util.putObject2Bucket(bucketName,fname,tempFile);
            this.deleteFile(tempPath + File.separator + fname);
            return rm;
        }catch (Exception e){
            rm.buildSystemErrorMessage();
            logger.debug(e.getMessage(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return rm;
        }
    }

    public boolean deleteFile(String sPath) {
        boolean flag = false;
        try{
            File file = new File(sPath);
            // 路径为文件且不为空则进行删除
            if (file.isFile() && file.exists()) {
                file.delete();
                flag = true;
            }
            logger.info("delete file seccess");
        }catch (Exception e){
            logger.info("delete file error");
            logger.info("delete file error resion :"+e);
        }
        return flag;
    }

    @Override
    public ResponseMessage<CurrentUserVo> getCurrentUser(Long accountId,String storagePublicAddr,String storagePublicPort,String bucketName) {
        //通过sessionId 从redis取到user_account表id
        ResponseMessage<CurrentUserVo> rm = new ResponseMessage<CurrentUserVo>();
        try {
            UserAccount userAccount = userAccountDao.selectByPrimaryKey(accountId);
            Long userId = userAccount.getUserId();
            CurrentUserVo currentUserVo = userDao.selectCurrentUser(userId);
            //从数据库里取出的头像名称md5值
            String profilePhoto = currentUserVo.getProfilePhoto();
            String profilePhotoUrl = "";
            if(StringUtils.isNotEmpty(profilePhoto)){
                profilePhotoUrl = "https://"+storagePublicAddr+":"+storagePublicPort+"/amazon-storage/download?bucketName="+bucketName+"&filename="+profilePhoto;
            }
            //拼接获取头像路径
            currentUserVo.setProfilePhoto(profilePhotoUrl);
            rm.setData(currentUserVo);
            return rm;
        }catch (Exception e){
            rm.buildSystemErrorMessage();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return rm;
        }
    }

    @Override
    public ResponseMessage<List<SelectBoxDataVo>> getShopSelectData(Long userId){
        ResponseMessage rm = new ResponseMessage<>();

        try {

        	boolean isSuperManager = isSuperManager(userId);
        	
            List<SelectBoxDataVo> m = new ArrayList<SelectBoxDataVo>();
            if(isSuperManager){
                m=shopDao.getShopSelectData(userId);
            }else{
            	m=shopDao.getCurrentUserShopSelectData(userId);
            }
            //SelectBoxDataVo selectBoxDataVo = new SelectBoxDataVo();
            //map.put(0L, "全部");
            //selectBoxDataVo.setId(0L);
            //selectBoxDataVo.setName("全部");

//             if (null != m &&) {
//            	 m.set(0, selectBoxDataVo);
//             }else{
//            	 m = new ArrayList<SelectBoxDataVo>();
//            	 m.set(0, selectBoxDataVo);
//             }
            rm.setData(m);
            return rm;
        } catch (Exception e) {
            logger.debug(e.getMessage(), e);
            rm.buildSystemErrorMessage();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return rm;
        }
    }


    @Override
    public ResponseMessage<UserEditDetailVo> getUserEditDetailById(Long id) {
        ResponseMessage rm = new ResponseMessage<>();
        if (null == id || id.intValue() < 0) {
            rm.buildParamErrorMessage();
            return rm;
        }
        try {
            UserEditDetailVo m = userDao.getUserEditDetail(id);
            if (null != m) {
                rm.setData(m);
            }
            return rm;
        } catch (Exception e) {
            logger.debug(e.getMessage(), e);
            rm.buildSystemErrorMessage();
            return rm;
        }
    }

    @Override
    public Long getCompanyId(Long userId){
        //Long userId = 1L;
        Long companyId = userDao.queryUserCompanyId(userId);
        return companyId;

    }

    @Override
    public void invalidateSession(FindByIndexNameSessionRepository<ExpiringSession> sessionRegistry, UnionUser user){
//        System.out.println(sessionRegistry.getAllSessions("test", true).size());
//        List<SessionInformation> sessionsInfo = sessionRegistry.getAllSessions("zwl", false);
        Map<String, ExpiringSession> sessionsInfo = sessionRegistry.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, user.getUsername());
        System.out.println(sessionsInfo.size());

        for (Map.Entry<String, ExpiringSession> entry: sessionsInfo.entrySet()) {
            String key = entry.getKey();
            ExpiringSession value = entry.getValue();
            sessionRegistry.delete(key);
            value.removeAttribute("user");

        }
       /* List<Object> o= sessionRegistry.getAllPrincipals();
        for (Object principal : o) {
            if (principal instanceof UnionUser) {
                final UnionUser loggedUser = (UnionUser) principal;
                if (user.getUsername().equals(loggedUser.getUsername())) {
                    List<SessionInformation> sessionsInfo = sessionRegistry.getAllSessions(principal, false);
                    if (null != sessionsInfo && sessionsInfo.size() > 0) {
                        for (SessionInformation sessionInformation : sessionsInfo) {
//                            sessionInformation.expireNow();
                            System.out.println(sessionInformation.getSessionId());
                        }
                    }
                }
            }
        }*/
    }
    
  public boolean isSuperManager(Long customerId) {
        
        try {
            int ret = userAccountDao.getSuperManager(customerId);
            if (0 == ret) {
               return false;
            }
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }

    @Override
    public ResponseMessage<GetCurrentShopVo> getCurrentShop(String channel, Long accountId) {
        ResponseMessage<GetCurrentShopVo> rm = new ResponseMessage<GetCurrentShopVo>();
        GetCurrentShopVo getCurrentShopVo = new GetCurrentShopVo();

        try{
            //如果用户有当前店铺显示当前店铺
            if(SysConstants.CHANNEL_APP.equals(channel)) {
                List<CurrentShopsVo> currentShopsVos = new ArrayList<CurrentShopsVo>();
                List<Module> mainModules = moduleDao.selectAppMainModule(accountId);
                Map<Long, List<Module>> maps = mainModules.stream().collect(Collectors.groupingBy(i -> i.getId()));
                List<Long> mainModuleIds = mainModules.stream().map(Module::getId).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(mainModuleIds)) {
                    List<CurrentModuleShopAccountVo> currentModuleShopAccountVos = currentShopDao.selectCurrentModuleShopAccount(accountId, mainModuleIds);
                    if (CollectionUtils.isNotEmpty(currentModuleShopAccountVos)) {
                        Map<Long, List<CurrentModuleShopAccountVo>> map2 = currentModuleShopAccountVos.stream().collect(Collectors.groupingBy(c -> c.getModuleId()));

                        //遍历所有有权限的APP模块
                        maps.forEach((k, v) -> {
                            //此k模块有当前店铺记录
                            if (map2.containsKey(k)) {
                                List<CurrentModuleShopAccountVo> cv = map2.get(k);
                                if (CollectionUtils.isNotEmpty(cv)) {
                                    CurrentShopsVo currentShopsVo = new CurrentShopsVo();
                                    currentShopsVo.setModuleCode(cv.get(0).getModuleCode());
                                    //ShopAccountVo shopAccountVo = new ShopAccountVo();
                                    currentShopsVo.setName(cv.get(0).getName());
                                    currentShopsVo.setCode(cv.get(0).getCode());
                                    currentShopsVo.setId(cv.get(0).getId());
                                    //currentShopsVo.setShopAccountVo(shopAccountVo);
                                    CurrentShop currentShop = new CurrentShop();
                                    currentShop.setModuleId(cv.get(0).getModuleId());
                                    currentShop.setCurrentShopId(cv.get(0).getId());
                                    //currentShop.setUserAccountId(accountId);
                                    currentShopsVos.add(currentShopsVo);
                                }
                            } else {
                                CurrentShopsVo currentShopsVo = new CurrentShopsVo();
                                currentShopsVo.setModuleCode(v.get(0).getModuleCode());
                                currentShopsVo.setId(-1L);
                                currentShopsVo.setCode("ALL");
                                currentShopsVo.setName("全部");
                                currentShopsVos.add(currentShopsVo);
                            }
                        });
                        getCurrentShopVo.setAppShops(currentShopsVos);
                    } else {
                        mainModules.forEach(m -> {
                            CurrentShopsVo currentShopsVo = new CurrentShopsVo();
                            currentShopsVo.setModuleCode(m.getModuleCode());
                            //currentShopsVo.setAll(true);
                            currentShopsVo.setId(-1L);
                            currentShopsVo.setCode("ALL");
                            currentShopsVo.setName("全部");
                            //currentShop.setUserAccountId(accountId);
                            currentShopsVos.add(currentShopsVo);
                        });
                        getCurrentShopVo.setAppShops(currentShopsVos);
                    }
                }
                rm.setData(getCurrentShopVo);
                return rm;
            }else{
                ShopAccount sa = shopAccountDao.selectByPrimaryKey(accountId);
                if(sa != null){
                    ShopAccountVo sav = new ShopAccountVo();
                    sav.setId(sa.getId());
                    sav.setCode(sa.getShopCode());
                    sav.setName(sa.getShopName());
                    getCurrentShopVo.setPadShop(sav);
                    rm.setData(getCurrentShopVo);
                }
                return rm;
            }

        }catch (Exception e){
            rm.buildSystemErrorMessage();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return rm;
        }
    }}
